package logic

import (
	"context"
	"net/http"
	"path/filepath"
	"shenzhou/B/api/pkg"
	"time"

	"shenzhou/B/api/internal/svc"
	"shenzhou/B/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type ImgLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewImgLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ImgLogic {
	return &ImgLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *ImgLogic) Img(req *http.Request) (resp *types.Response, err error) {
	// todo: add your logic here and delete this line
	file, m, err := req.FormFile("img")
	if err != nil {
		return &types.Response{
			Code: 500,
			Msg:  err.Error(),
			Data: nil,
		}, nil
	}

	if m.Size > 1*1024*1024 {
		return &types.Response{
			Code: 500,
			Msg:  "文件大小不能超过1MB",
			Data: nil,
		}, nil
	}

	ext := filepath.Ext(m.Filename)

	if ext != ".jpg" {
		return &types.Response{
			Code: 500,
			Msg:  "文件类型必须是.jpg文件",
			Data: nil,
		}, nil
	}

	name := time.Now().Format("20060102150405") + ext
	upload, err := pkg.Upload(file, name)
	if err != nil {
		return &types.Response{
			Code: 500,
			Msg:  err.Error(),
			Data: nil,
		}, nil
	}

	return &types.Response{
		Code: 200,
		Msg:  "图片上传成功",
		Data: map[string]interface{}{
			"upload": upload,
		},
	}, nil
}
